package com.star.robot.controller;

import com.star.robot.dto.PageResultDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.dto.TeamMemberQueryDto;
import com.star.robot.dto.TeamMemberRespDto;
import com.star.robot.entity.DtArea;
import com.star.robot.entity.Team;
import com.star.robot.entity.TeamLeader;
import com.star.robot.entity.TeamMember;
import com.star.robot.enums.AdminTypeEnum;
import com.star.robot.enums.CompanyTypeEnum;
import com.star.robot.enums.ProjectClassEnum;
import com.star.robot.enums.ProjectLevelEnum;
import com.star.robot.repository.DtAreaRepositoty;
import com.star.robot.repository.TeamMemberRepository;
import com.star.robot.service.AdminService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 队员管理
 */
@RestController
@RequestMapping(value = "/team/member")
@Slf4j
public class TeamMemberController {


    @Autowired
    private TeamMemberRepository teamMemberRepository;


    @Autowired
    private DtAreaRepositoty dtAreaRepositoty;

    @Autowired
    private AdminService adminService;


    @GetMapping(value = "/")
    @ApiOperation(value = "队员查询",notes = "队员查询")
    public PageResultDto get(TeamMemberQueryDto requestDto, HttpServletRequest request){
        PageResultDto<TeamMemberRespDto> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());

            Page<TeamMember> pageable = teamMemberRepository.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                    List<Predicate> conditions = new ArrayList<>();

                    //项目id
                    if(requestDto.getProjectId() != null){
                        Predicate projectCond = cb.equal(root.get("team").get("project").get("id") , requestDto.getProjectId());
                        conditions.add(projectCond);
                    }


                    //项目名称
//                    if(!StringUtils.isEmpty(requestDto.getProjectName())){
//                        Predicate cityCondition = cb.equal(root.get("team").get("project").get("name")  , "%"+requestDto.getProjectName()+"%");
//                        conditions.add(cityCondition);
//                    }
                    AdminTypeEnum adminTypeEnum = adminService.getCurrentAdminLevel(request);
                    log.info("队员管理查询　：　参数[adminTypeEnum] :"+adminTypeEnum.getName());
                    if(adminTypeEnum == AdminTypeEnum.PROVINCEADMIN){
                        Predicate adminTypeCond = cb.equal(root.get("team").get("project").get("projectLevelEnum") , ProjectLevelEnum.PROVINCELEVEL);
                        conditions.add(adminTypeCond);
                    }else{
                        Predicate adminTypeCond = cb.equal(root.get("team").get("project").get("projectLevelEnum") , ProjectLevelEnum.PROVINCELEVEL);
                        conditions.add(adminTypeCond);

                        //市
                        Long cityId = adminService.getCurrentAdminCityId(request);
                        log.info("队员管理查询　：　参数[cityId] :"+cityId);
                        if(cityId != null){
                            Predicate cityCondition = cb.equal(root.get("team").get("company").get("cityId")  , cityId);
                            conditions.add(cityCondition);
                        }
                    }

                    //区
//                    if(requestDto.getAreaId() != null){
//                        Predicate areaCondition = cb.equal(root.get("team").get("company").get("areaId")  , requestDto.getAreaId());
//                        conditions.add(areaCondition);
//                    }
                    //队员姓名
                    if(!StringUtils.isEmpty(requestDto.getTeamMemberName())){
                        Predicate memberNameCond = cb.like(root.get("name")  , "%"+requestDto.getTeamMemberName()+"%");
                        conditions.add(memberNameCond);
                    }
                    //队员身份证
                    if(!StringUtils.isEmpty(requestDto.getTeamMemberIdCard())){
                        Predicate memberIdCardCond = cb.like(root.get("idCard")  , "%"+requestDto.getTeamMemberIdCard()+"%");
                        conditions.add(memberIdCardCond);
                    }
                    //单位名称
                    if(!StringUtils.isEmpty(requestDto.getCompanyName())){
                        Predicate companyCond = cb.like(root.get("team").get("company").get("name") , "%"+requestDto.getCompanyName() +"%");
                        conditions.add(companyCond);
                    }
                    //队伍名称
                    if(!StringUtils.isEmpty(requestDto.getTeamName())){
                        Predicate teamNameCond = cb.like(root.get("team").get("teamName") , "%"+requestDto.getTeamName()+"%");
                        conditions.add(teamNameCond);
                    }
                    //单位性质
                    if(requestDto.getCompanyType() !=null){
                        CompanyTypeEnum companyType = null;
                        if(requestDto.getCompanyType().intValue() == 1){
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }else if(requestDto.getCompanyType().intValue() == 2){
                            companyType =  CompanyTypeEnum.JIGOU;
                        }else{
                            //默认学校
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }
                        Predicate companyTypeCond = cb.equal(root.get("team").get("company").get("companyType") ,companyType);
                        conditions.add(companyTypeCond);

                    }

                    //报名时间 => 队伍　新增时间
                    if(!StringUtils.isEmpty(requestDto.getBaoMingDateStart())
                           ){
                        Predicate baoMingDateCond = cb.greaterThan(root.get("team").get("project").get("baoMingStartTime") ,requestDto.getBaoMingDateStart());
                        conditions.add(baoMingDateCond);
                    }
                    if(!StringUtils.isEmpty(requestDto.getBaoMingDateEnd())
                    ){
                        Predicate baoMingDateCond = cb.lessThan(root.get("team").get("project").get("baoMingEndTime") , requestDto.getBaoMingDateEnd());
                        conditions.add(baoMingDateCond);
                    }
                    //参赛类别
                    //大类
//                    if(requestDto.getClass1Id() != null){
//                        Predicate class1IdCond = cb.equal(root.get("team").get("class1Id") ,requestDto.getClass1Id());
//                        conditions.add(class1IdCond);
//                    }
//                    //小类
//                    if(requestDto.getClass2Id() != null){
//                        Predicate class2IdCond = cb.equal(root.get("team").get("class2Id") ,requestDto.getClass2Id());
//                        conditions.add(class2IdCond);
//                    }
                    //组别
                    if(requestDto.getGroupType() != null){
                        ProjectClassEnum projectClassEnum = null;
                        if(requestDto.getGroupType() == 1){
                            projectClassEnum = ProjectClassEnum.XIAOXUE;
                        }else if(requestDto.getGroupType() == 2){
                            projectClassEnum = ProjectClassEnum.CHUZHONG;
                        }else if(requestDto.getGroupType() == 3){
                            projectClassEnum = ProjectClassEnum.GAOZHONG;
                        }else{
                            //默认小学组
                            projectClassEnum = ProjectClassEnum.XIAOXUE;
                        }
                        Predicate groupTypeCond = cb.equal(root.get("team").get("projectClassEnum") ,projectClassEnum);
                        conditions.add(groupTypeCond);
                    }
                    if(requestDto.getSizeEnum() != null){
                        Predicate sizeCond = cb.equal(root.get("size") ,requestDto.getSizeEnum());
                        conditions.add(sizeCond);
                    }

                    Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);



            List<TeamMemberRespDto> teamMemberRespDtos = new ArrayList<>();
            List<TeamMember> teamMembers = pageable.getContent();
            if(!CollectionUtils.isEmpty(teamMembers)){
                for(TeamMember teamMember : teamMembers){
                    String companyType = teamMember.getTeam().getCompany().getCompanyType().getName();
                    String companyName = teamMember.getTeam().getCompany().getName();
                    String teamName = teamMember.getTeam().getTeamName();
                    String projectType = teamMember.getTeam().getProjectClassEnum().getName();
                    String projectName = teamMember.getTeam().getProject().getName();

                    String areaName = null;
                    String cityName = null;
                    if(teamMember.getTeam().getCompany().getAreaId() != null ){

                        DtArea area = dtAreaRepositoty.findById(Long.valueOf(teamMember.getTeam().getCompany().getAreaId())).get();
                        DtArea city = dtAreaRepositoty.findById(Long.valueOf(teamMember.getTeam().getCompany().getCityId())).get();
                        areaName = area != null ? area.getAreaName() : null;
                        cityName = city != null ? city.getAreaName() : null;
                    }





                    TeamMemberRespDto teamTeamMemberRespDto = TeamMemberRespDto.builder()
                            .id(teamMember.getId())
                        .companyType(companyType)
                            .companyName(companyName)
                            .teamName(teamName)
                            .projectType(projectType)
                            .groupType(projectName)
                            .name(teamMember.getName())
                            .sex(teamMember.getSex() == 1 ?"男" :"女")
                            .idCard(teamMember.getIdCard())
                            .size(teamMember.getSize().getName())
                            .school(teamMember.getSchool())
                            .areaName(areaName)
                            .cityName(cityName)
                            .build();
                    teamMemberRespDtos.add(teamTeamMemberRespDto);
                }

            }

            Page pagedTeamMembers = new PageImpl(teamMemberRespDtos , page ,pageable.getTotalElements() );


            results.setData(pagedTeamMembers.getContent());
            results.setCount(pagedTeamMembers.getTotalElements());
            return results;
        }
        return PageResultDto.builder().data(null).build();
    }

    @GetMapping(value = "/teamId")
    @ApiOperation(value = "队伍队员查询",notes = "队伍队员查询")
    public ResultDto getTeamMember(TeamMemberQueryDto teamMemberQueryDto) {

        if(teamMemberQueryDto.getTeamId() != null){
            List<TeamMember> teamMembers =  teamMemberRepository.getByTeamId(teamMemberQueryDto.getTeamId());

            if(!CollectionUtils.isEmpty(teamMembers)){
                for(TeamMember teamMember : teamMembers){
                    teamMember.setTeam(null);
                }
            }
            return ResultDto.builder().data(teamMembers).build();
        }
        return ResultDto.builder().data(null).build();

    }


    /**
     *
     * @param teamId
     * @param member
     * @param leader
     * @return
     */
    @GetMapping(value = "/modifyMember")
    @ApiOperation(value = "修改队员信息",notes = "修改队员")
    public ResultDto modifyMember(String teamId, TeamMember member, TeamLeader leader) {

        //TODO
        return null;
    }

    /**
     *
     * @param
     * @param
     * @param
     * @return
     */
    @PostMapping(value = "/modifyMemberBack")
    @ApiOperation(value = "修改队员信息",notes = "修改队员")
    public ResultDto modifyMember(@RequestBody TeamMember teamMember) {

        TeamMember oldMember = this.teamMemberRepository.findByIdCard(teamMember.getIdCard());
        Team oldTeam = oldMember.getTeam();
        if(oldMember != null){
            teamMember.setTeam(oldTeam);
            teamMember.setId(oldMember.getId());
            teamMemberRepository.save(teamMember);
        }
        return ResultDto.builder().build();
    }

    /**
     *
     * @param member
     * @return
     */
    @DeleteMapping(value = "/modifyMember")
    @ApiOperation(value = "删除队员信息",notes = "删除队员")
    public ResultDto deleteMember(TeamMember member) {

        teamMemberRepository.delete(member);
        return ResultDto.builder().build();
    }

}
